package com.qf.study.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author GSh
 * @packageName:com.qf.study.utils
 * @className:MyBatisUtils
 * @description  工具类
 * @create 2021-07-29 15:53
 */
public class MyBatisUtils {

        private static SqlSessionFactory sqlSessionFactory;

        private static final ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();

        static {
            try {
                InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static SqlSession getSqlSession(){
            SqlSession sqlSession = tl.get();
            if(sqlSession==null){
                sqlSession = sqlSessionFactory.openSession();
                tl.set(sqlSession);
            }
            return sqlSession;
        }
        public static void closeSqlSession(){
            SqlSession sqlSession = tl.get();
            sqlSession.close();
            tl.remove();
        }
        public static void commit(){
            SqlSession sqlSession = tl.get();
            sqlSession.commit();
            closeSqlSession();
        }
        public static void rollback(){
            SqlSession sqlSession = tl.get();
            sqlSession.rollback();
            closeSqlSession();
        }
        public static <T extends Object> T getMapper(Class<T> clazz){
            SqlSession sqlSession = getSqlSession();
            T mapper = sqlSession.getMapper(clazz);
            return mapper;
        }
}
